package com.glsc.ngateway.opmanage.service.outsys;


import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemTemplateRel;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.outsys.OutSystemTemplateRelRepository;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class OutSystemTemplateRelService {

    @Resource
    private OutSystemTemplateRelRepository relRepositorys;

    @Resource
    private OutSystemAuthTemplateService outSystemAuthTemplateService;

    /**
     * 分页
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<OutSystemTemplateRel> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<OutSystemTemplateRel> page = relRepositorys.findAll(SpecificationUtil.buildSpecification(param, OutSystemTemplateRel.class), pageable);
        return page;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    public OutSystemTemplateRel save(OutSystemTemplateRel obj) {
        return relRepositorys.save(obj);
    }

    public List<OutSystemTemplateRel> saveAll(List<OutSystemTemplateRel> list) {
        return relRepositorys.saveAll(list);
    }

    /**
     * 根据地查找
     *
     * @param id
     * @return
     */
    public OutSystemTemplateRel findSimpleInfoById(Integer id) {
        Optional<OutSystemTemplateRel> optional = relRepositorys.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据末班id查询所有的系统关联信息
     *
     * @param templateId
     * @return
     */
    public List<OutSystemTemplateRel> findByTemplateId(Integer templateId, Integer sysId) {
        OutSystemTemplateRel build = OutSystemTemplateRel.builder().templateId(templateId).build();
        if (Objects.nonNull(sysId)) {
            build.setSysId(sysId);
        }
        return relRepositorys.findAll(Example.of(build));
    }

    public List<OutSystemTemplateRel> findBySystemId(Integer sysId) {
        OutSystemTemplateRel build = OutSystemTemplateRel.builder().sysId(sysId).build();
        return relRepositorys.findAll(Example.of(build));
    }


    /**
     * 根据id删除
     *
     * @param id
     */
    public void deleteById(Integer id) {
        relRepositorys.deleteById(id);
    }


}
